package ru.mcfr.oxygen.framework.operations.table;

import org.apache.log4j.Logger;
import ro.sync.ecss.extensions.api.*;

import javax.swing.*;
import java.awt.*;

public class InsertTableOperation implements AuthorOperation {

    private static Logger logger = Logger.getLogger(InsertTableOperation.class.getName());

    private TableInfo tableInfo = null;

    private String getBorderInfoForCell(int x, int y, String type) {
        String key = "";

        if (type.equals("все")) {
            if (x == 0 & y == 0)
                key = "ltbr";

            if (x == 0 & y > 0)
                key = "tbr";

            if (x > 0 & y == 0)
                key = "lbr";

            if (x > 0 & y > 0)
                key = "br";
        }

        if (type.equals("левая"))
            if (y == 0)
                key = "l";

        if (type.equals("верхняя"))
            if (x == 0)
                key = "t";

        if (type.equals("правая"))
            if (y == tableInfo.getColumnsNumber() - 1)
                key = "r";

        if (type.equals("нижняя"))
            if (x == tableInfo.getRowsNumber() - 1)
                key = "b";

        String border = "";

        if (key.contains("l"))
            border += "border-left=\"1px solid #000000\" ";

        if (key.contains("r"))
            border += "border-right=\"1px solid #000000\" ";

        if (key.contains("t"))
            border += "border-top=\"1px solid #000000\" ";

        if (key.contains("b"))
            border += "border-bottom=\"1px solid #000000\" ";

        int size = border.length();
        if (size > 0)
            return border.substring(0, size - 1);
        else
            return "";
    }

    public void doOperation(AuthorAccess authorAccess, ArgumentsMap args) throws IllegalArgumentException, AuthorOperationException {
        final AuthorSchemaManager schemaManager = authorAccess.getDocumentController().getAuthorSchemaManager();
        AuthorDocumentController controller = authorAccess.getDocumentController();

        //TODO сделать генерацию фрагмента из схемы

        TableInfo initTableInfo = new TableInfo(0, 0, 0, 0);
        initTableInfo.addCellContent("обобщающий текст", "<обобщающий_текст id=\"\"/>");
        initTableInfo.addCellContent("пункт", "<пункт id=\"\"/>");
        initTableInfo.addCellContent("абзац", "<абзац id=\"\"/>");
        if (authorAccess.getWorkspaceAccess().isStandalone()) {
            TableCustomizerDialog tableCustomizerDialog = new TableCustomizerDialog((JFrame) authorAccess.getWorkspaceAccess().getParentFrame());
            tableCustomizerDialog.setLocationRelativeTo((Component) authorAccess.getWorkspaceAccess().getParentFrame());
            tableInfo = tableCustomizerDialog.showDialog(initTableInfo);
        }

        if (tableInfo != null) {
            // Create the table XML fragment

//			try {
//				int currentPosition = authorAccess.getCaretOffset();
//				WhatElementsCanGoHereContext neededElements = schemaManager.createWhatElementsCanGoHereContext(currentPosition);   
//				List<CIElement> allPossibleElements = schemaManager.whatElementsCanGoHere(neededElements);
//				AuthorDocumentFragment frag = null;
//				logger.error("all possible elements count: " + allPossibleElements.size());
//				for (int i = 0; i < allPossibleElements.size(); i++) {
//					CIElement currentElement = allPossibleElements.get(i);
//					if ("таблица".equals(currentElement.getQName())) {
//						logger.error("we find table element");
//						frag = schemaManager.createAuthorDocumentFragment(currentElement);
//						logger.error("create element adapter for table");
//						AuthorDocumentFragment fragment = schemaManager.createAuthorDocumentFragment((CIElement) frag);
//						logger.error("get fragment for created element table");
//						List<AuthorNode> nodes = fragment.getContentNodes();
//						for (AuthorNode node : nodes){
//							AuthorElement aeNode = (AuthorElement) node;
//							logger.error("element name - " + aeNode.getName());
//							List<AuthorNode> morenodes = aeNode.getContentNodes();
//							for (AuthorNode moreNode : morenodes){
//								AuthorElement moreAeNode = (AuthorElement) moreNode;
//								logger.error("element name - " + moreAeNode.getName());
//							}
//						}
//						break;
//
//					}
//				}
//			} catch (BadLocationException e) {
//				logger.error(e.getMessage());
//			} catch (Exception e){
//				logger.error(e.getMessage());
//			}


            StringBuffer tableXMLFragment = new StringBuffer();
            tableXMLFragment.append("<таблица id=\"\" border-collapse=\"\">");

            tableXMLFragment.append("<группировка_колонок id=\"\">");

            for (int k = 0; k < tableInfo.getColumnsNumber(); k++) {
                tableXMLFragment.append("<колонка width=\"50px\" id=\"\"/>");
            }

            tableXMLFragment.append("</группировка_колонок>");

            for (int i = 0; i < tableInfo.getRowsNumber(); i++) {

                tableXMLFragment.append("<строка id=\"\"");

                if (i < tableInfo.getHeaderRowsCount())
                    tableXMLFragment.append(" тип_строки=\"шапка\"");

                else if (i > tableInfo.getRowsNumber() - tableInfo.getFooterRowsCount() - 1)
                    tableXMLFragment.append(" тип_строки=\"подвал\"");

                tableXMLFragment.append(">");

                for (int j = 0; j < tableInfo.getColumnsNumber(); j++) {

                    String borderInfo = "";
                    borderInfo = getBorderInfoForCell(i, j, tableInfo.getTypeOfBorder());
                    if (!borderInfo.isEmpty())
                        borderInfo = " " + borderInfo;

                    if (tableInfo.getFuck() == "")
                        tableXMLFragment.append("<ячейка id=\"\"/" + borderInfo + ">");

                    else
                        tableXMLFragment.append("<ячейка id=\"\"" + borderInfo + ">" + tableInfo.getFuck() + "</ячейка>");

                }

                tableXMLFragment.append("</строка>");
            }

            tableXMLFragment.append("</таблица>");

            logger.error(tableXMLFragment.toString());

            controller.insertXMLFragmentSchemaAware(tableXMLFragment.toString(), authorAccess.getEditorAccess().getCaretOffset());

        }
    }

    /**
     * No arguments. The operation will display a dialog for choosing the table
     * attributes.
     *
     * @see ro.sync.ecss.extensions.api.AuthorOperation#getArguments()
     */
    public ArgumentDescriptor[] getArguments() {
        return null;
    }

    /**
     * @see ro.sync.ecss.extensions.api.Extension#getDescription()
     */
    public String getDescription() {
        return "Insert a SDF table";
    }
}